package Leave

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"project/pkg/models"
	"project/pkg/validate"
	"strconv"
)

func (h LHandler) DeleteLeave(c *gin.Context) {
	resp := new(models.RespData)
	req := new(models.DeleteLeaveReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("Leave:DeleteLeave with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("Leave:DeleteLeave with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	//删除
	err := h.M.LeaveDeleteByID(strconv.Itoa(req.LeaveId))
	if err != nil {
		zap.L().Error("Leave:DeleteLeave h.M.LeaveDeleteByID err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	//修改学生
	exist, info, err := h.M.StudentCheckExistByOpenID(req.WxOpenID)
	if err != nil {
		zap.L().Error("Leave:DeleteLeave h.M.StudentCheckExistByOpenID err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	if exist {
		count, _ := strconv.Atoi(info.LeaveInfoCount)
		now := count - 1
		info.LeaveInfoCount = strconv.Itoa(now)
		err := h.M.StudentUpdateInfoBuID(info)
		if err != nil {
			zap.L().Error("Leave:UpdateInfo h.M.StudentUpdateInfoBuID err", zap.Error(err))
			resp.SendServerBusy(c)
			return
		}
	}
	resp.SendSuccess(c)
}
